<template>
  <!-- 上传组件 -->
  <el-upload
    v-if="type == 'img'"
    list-type="picture-card"
    :show-file-list="multiple"
    :action="uploadUrl"
    :accept="acceptType['img']"
    :on-preview="uploadPreview"
    :on-remove="uploadRemove"
    :on-success="uploadSuccess"
    :before-remove="uploadBeforeRemove"
    :multiple="multiple"
    :file-list="uploadFileList"
  >
    <i v-if="!editValue.url || multiple" class="el-icon-plus"></i>
    <img v-else class="avatar" :src="editValue.url" />
  </el-upload>
  <el-upload
    v-else
    :action="uploadUrl"
    :accept="acceptType[accept]"
    :on-preview="uploadPreview"
    :on-remove="uploadRemove"
    :on-success="uploadSuccess"
    :before-remove="uploadBeforeRemove"
    :multiple="multiple"
    :file-list="uploadFileList"
  >
    <el-button size="small" type="primary" icon="el-icon-upload"
      >点击上传</el-button
    >
    <div v-if="placeholder" slot="tip" class="el-upload__tip">
      {{ placeholder }}
    </div>
  </el-upload>
</template>

<script>
const accept = {
  img: ".jpg, .jpeg, .png, .gif, .bmp",
  pdf: ".pdf",
  office: ".doc .docx .xls .xlsx .ppt .pptx",
  all: "*",
};
export default {
  props: {
    //v-model绑定
    value: {
      type: [String, Array, Object],
      required: true,
    },
    //类型
    type: {
      type: String,
      validator: function(value) {
        return ["upload", "img"].findIndex((item) => item == value) >= 0;
      },
    },
    //输入前提示语
    placeholder: String,
    //upload,img是否可以选择多个文件
    multiple: { type: Boolean, default: false },
    //upload,img 上传地址
    uploadUrl: String,
    //upload的文件类型，目前有 img,office,pdf,all
    accept: { type: String, default: "all" },
  },
  data() {
    return {
      editValue: this.value,
      acceptType: accept,
      uploadFileList: [],
    };
  },
  methods: {
    uploadRemove(file, fileList) {
      console.log(file, fileList);
      /**
       * TODO: 需要调用后台删除的api
       */
    },
    uploadPreview(file) {
      /**
       * TODO: 上传预览，可以弹出一个预览窗口组件
       */
    },
    uploadBeforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    uploadSuccess(res, file, fileList) {
      if (this.type == "img" && !this.multiple) {
        this.editValue = file
      } else {
        this.editValue = fileList;
      }
      /**
       * 上传成功后应该给editValue赋值下载或显示的url
       */
    },
  },
  watch: {
    editValue(val) {
      this.$emit("input", val);
    },
    value(val){
      this.editValue = val
    }
  },
};
</script>

<style lang="less" scoped>
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>
